<template>
  <div v-loading="loading" class="container">
    <div class="block" style="float: left;width: 350px;">
      <el-input v-model="word" placeholder="请输入内容" class="input-with-select" clearable>
        <el-button slot="append" icon="el-icon-search" @click="handleSearch" />
      </el-input>
    </div>
    <div class="block" style="float: right">
      <el-pagination
        :current-page.sync="pageNo"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        @current-change="turnPage"/>
    </div>
    <el-table
      :data="list"
      height="650px"
      stripe
      style="width: 100%">
      <el-table-column
        label="名称"
        width="300px"
        header-align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        label="描述"
        header-align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.desc }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        label="地址"
        header-align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="图片"
        align="center">
        <template slot-scope="scope">
          <el-image
            v-for="(item) in scope.row.photos"
            :key="item.id"
            :src="item.img_url"
            style="width: 50px; height: 50px;margin-left:10px"
            fit="fill"
            lazy
            @click="previewImage(item)">
            <div slot="error" class="image-slot" @click="previewImage(item)">
              <i class="el-icon-picture-outline" />
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px" header-align="center">
        <template slot-scope="scope">
          <div style="display: inline-block">
            <el-button
              size="mini"
              @click="handleEdit(scope.row.id)"
            >编辑 </el-button>
            <el-upload
              :action="uploadPhotoUrl"
              :file-list="fileList"
              :data="{id: scope.row.id}"
              :http-request="handleUploadBefore"
              :show-file-list="false">
              <el-button size="mini">上传图片</el-button>
            </el-upload>
            <el-button
              size="mini"
              @click="handleNews(scope.row.id)"
            >相关资讯</el-button>
            <!-- <el-button
              size="mini"
              @click="handleAddNews(scope.row.id)"
            >创建资讯</el-button> -->
          </div>
          <!--<el-button-->
          <!--size="mini"-->
          <!--@click="handleEdit(scope.row.id)">编辑</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-dialog :visible.sync="dialogVisible">
        <div class="preview-area">
          <div class="photo-remove">
            <span class="remove-btn">
              <el-button type="danger" icon="el-icon-delete" circle @click="handleRemovePhoto"/>
            </span>
            <span class="left" @click="handleSortPhoto('down')"><i style="font-size:50px" class="el-icon-back"/></span>
            <span class="right" @click="handleSortPhoto('up')"><i style="font-size:50px" class="el-icon-right" /></span>
          </div>
          <img :src="dialogImageUrl" width="100%" alt="" style="min-height:100px">
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { init, search, removePhoto, sortPhoto } from '@/api/common'
import { _hostUrl } from '@/utils/aws1903'
import * as ImgCompress from '@/utils/photoCompress'

export default {
  name: 'Dashboard',
  data() {
    return {
      loading: false,
      list: [],
      dialogVisible: false,
      dialogImageId: 0,
      dialogImageUrl: '',
      uploadPhotoUrl: _hostUrl + '/bs/uploadPhoto',
      pageSize: 10,
      pageNo: 1,
      total: 1462,
      word: '',
      fileList: []
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'roles'
    ])
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      if (this.$route.query.back && localStorage.getItem('word')) {
        this.word = localStorage.getItem('word')
        console.log('set word', this.word)
        delete this.$route.query.back
        this.handleSearch()
        return
      } else if (this.$route.query.back && localStorage.getItem('pageNo')) {
        this.pageNo = parseInt(localStorage.getItem('pageNo'))
        console.log('set pageno', this.pageNo)
        delete this.$route.query.back
      }
      this.loading = true
      init(this.pageNo - 1).then(response => {
        this.list = response.data.list
        this.pageSize = response.data.pageSize
        this.total = response.data.total
        this.loading = false
        localStorage.setItem('pageNo', this.pageNo)
      }).catch(reason => {
        console.error(reason)
        this.loading = false
      })
    },

    turnPage() {
      this.loading = true
      // 如果输入框有东西，则调用 searchWord
      if (this.word !== '') {
        this.searchWord()
        return
      }

      this.initData(this.pageNo - 1)
    },

    handleUploadBefore(req) {
      this.loading = true
      const that = this
      const newFile = req.file
      const imgName = newFile.name
      ImgCompress.photoCompress(newFile, { quality: this.currentQuality }, function(blob) {
        const { lastModified, type } = newFile
        const compress_file = new File([blob], imgName, { type: type, lastModified: lastModified })
        console.log('compress_file size: ' + compress_file.size)
        // FormData 对象
        var form = new FormData()
        // 文件对象
        form.append('file', compress_file)
        // 其他参数
        form.append('id', req.data.id)
        // XMLHttpRequest 对象
        var xhr = new XMLHttpRequest()
        xhr.open('post', req.action, true)
        const id = req.data.id
        xhr.onload = function() {
          const res = JSON.parse(xhr.response)
          that.list.forEach(item => {
            if (item.id === id) {
              console.log(res)
              item.img_url = res.url
            }
          })

          that.$message({
            message: '恭喜你，上传成功!',
            type: 'success'
          })
          that.loading = false
          if (that.word) {
            that.$route.query.back = 1
          }
          that.initData()
        }
        xhr.onerror = () => {
          that.loading = false
        }
        xhr.send(form)
      })
    },

    handleUploadChange(file, fileList) {
      console.log('in change...', file, fileList)
    },

    previewImage(photo) {
      if (photo) {
        this.handlePictureCardPreview(photo.id, photo.img_url)
      }
    },

    handlePictureCardPreview(id, url) {
      this.dialogImageId = id
      this.dialogImageUrl = url
      this.dialogVisible = true
    },
    handleEdit(id) {
      this.$router.push({ path: '/place/edit', query: { id: id }})
    },
    handleNews(id) {
      this.$router.push({ path: '/news/list', query: { placeId: id }})
    },
    handleAddNews(id) {
      this.$router.push({ path: '/news/addNew', query: { placeId: id }})
    },

    handleRemovePhoto() {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removePhoto(this.dialogImageId).then(() => {
          if (this.word) {
            this.$route.query.back = 1
          }
          this.initData()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.dialogVisible = false
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '删除失败'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    handleSortPhoto(direction) {
      sortPhoto(this.dialogImageId, direction).then(() => {
        if (this.word) {
          this.$route.query.back = 1
        }
        this.initData()
      })
    },

    handleSearch() {
      this.pageNo = 1
      if (this.word !== '') {
        this.searchWord()
      } else {
        localStorage.setItem('word', '')
        this.initData()
      }
    },

    searchWord() {
      this.loading = true
      search(this.pageNo - 1, this.word).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.loading = false
        localStorage.setItem('word', this.word)
      }).catch(reason => {
        console.error(reason)
        this.loading = false
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .container {
    margin: 30px;
    &-text {
      font-size: 25px;
      line-height: 40px;
    }
    &-instruction {
      font-size: 15px;
      font-style: italic;
      line-height: 25px;
      color: #99a9bf;
    }
  }
  .container .preview-area .photo-remove {
    display: none;
    position: absolute;
    width: 96%;
    height: 88%;
    background: #000000;
    opacity: 0.5;
   .remove-btn {
      display: block;
      position: absolute;
      width: 50px;
      height: 50px;
      left: 0;
      right: 0;
      bottom: 0;
      top: 0;
      margin: auto;
    }
    .left {
      cursor: pointer;
      width: 100px;
      height: 100px;
      display: block;
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      margin: auto;
    }
    .right {
      cursor: pointer;
      width: 100px;
      height: 100px;
      display: block;
      position: absolute;
      right: 0;
      top: 0;
      bottom: 0;
      margin: auto;
    }
  }
  .container .preview-area:hover .photo-remove{
    display: block;
  }
</style>
